'''
金色重阳防癌疾病保险
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests,time,random
from pyquery import PyQuery as pq
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "金色重阳防癌疾病保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄段
                "year": [str(i) for i in range(50,76)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["10000", "50000", "100000", "150000", "200000"],
                # 保障期限
                "expire": ["5年"],
                # 缴费间隔
                "interval": ["0", "3", "5"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(50, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["10000", "50000", "100000", "150000", "200000"],
                # 保障期限
                "expire": ["10年","15年","20年"],
                # 缴费间隔
                "interval": ["0", "3", "5","10"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["interval"]):
                if v[4] == "0":
                    payType = "一次缴清"
                else:
                    payType = "年缴"

                #写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],payType
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],payType
                ))
    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "age": dt["year"],
            "gender": "男" if dt["gender"] == "M" else "女",
            "insured": dt["money"],
            "pay_period": "趸交" if dt["interval"] == "0" else dt["interval"] + "年交",
            "insurance_period": dt["expire"],
        }

        prefix = urlencode(data).replace("+","")
        r = requests.get( url = domain[self.name]["url"] + prefix,headers=domain[self.name]["header"])
        if r.status_code == 200  and "暂无价格" not in r.text:
            price = Helper.decimalParse(self.parseJson( r.text ))
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])


    #提取价格数据
    def parseJson(self,html=None):

        doc = pq(html)
        price = doc(".i-card").text().split("\n")[0].replace(" 元/年","").replace("￥ ","")

        return price
    # 执行主程序
    def main(self):

        while True:
            time.sleep(2)
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
